package Long.Lu.Service.Impl;


import Long.Lu.Dao.UserInfoDao;
import Long.Lu.Service.LoginService;
import Long.Lu.pojo.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @ClassName:
 * @description:
 * @author: yh
 * @createDate: 2020/10/24
 * @version: 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {
    /*注入userInfoDao*/
    @Autowired
    private UserInfoDao userInfoDao;

    @Override
    public HashMap<String, Object> loginShiro(UserInfo userInfo, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<>();
        UserInfo user = userInfoDao.findByUserName(userInfo.getUserName());
        /*判断账号是否存在*/
        if (user != null) {
            /*验证密码*/
            try {
                /*1.创建令牌*/
                UsernamePasswordToken token=new UsernamePasswordToken(userInfo.getUserName(),userInfo.getUserPwd());
                /*2.获取shrio的用户对象*/
                Subject subject= SecurityUtils.getSubject();
                /*3.shrio登录*/
                subject.login(token);
                /*创建session对象*/
                HttpSession session = request.getSession();
                /*存入session*/
                session.setAttribute("userInfo", user);
                map.put("info", true);
                return map;
            } catch (AuthenticationException e) {
                map.put("info", "密码输入错误");
                e.printStackTrace();
            }

        } else {
            map.put("info", "无此账号");
        }

        return map;
    }

    /*在使用shiro框架需要用户密码，查询密码*/
    @Override
    public UserInfo selectByName(String userName) {
        return userInfoDao.findByUserName(userName);
    }
}
